package cn.laixueit.export.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.word.Word07Writer;
import cn.laixueit.utils.ExportWordUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;

/**
 * @author duxiang
 * @date 2023/11/29 17:22
 */
@Service
public class FileExportService {

    @Resource
    private ExportWordUtils exportWordUtils;

    /**
     * 导出素有内容为word,当前为book
     * @param ids 主id集合
     * @param response
     */
    public void downLoadWordList(List<String> ids, HttpServletResponse response) {
        Word07Writer writer = new Word07Writer();
        LinkedList<Map<String, List>> wordText = exportWordUtils.createWordText(ids);
        for (Map<String, List> map : wordText) {
            Set<String> set = map.keySet();
            String bname = set.iterator().next();
            writer.addText(new Font("方正小标宋简体", Font.TYPE1_FONT, 22), bname);
            List<Map<String,String>> list = map.get(bname);
            for (Map<String, String> m : list) {
                Set<String> keySet = m.keySet();
                for (String s : keySet) {
                    String content = m.get(s);
                    writer.addText(new Font("方正小标宋简体", 2, 16), s);
                    writer.addText(new Font("方正小标宋简体", Font.PLAIN, 12), content);
                }
            }
        }
        try {
            ServletOutputStream out = null;
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String finalName = URLEncoder.encode("软件列表", "UTF-8") + "_" + DateUtil.today();
            response.setHeader("Content-disposition", "attachment;filename=" + finalName + ".xlsx");
            out = response.getOutputStream();

            writer.flush(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
